#include "mainwindow.h"
#include "usermanager.h"
#include "uiobjectreader.h"
#include "userconfigmanager.h"
#include "filedialoghandler.h"
#include "jsonconfigwriter.h"

#include "ui_mainwindow.h"

#include <QDebug>
#include <QStringList>
#include <QFileDialog>
#include <QMessageBox>
#include <QListView>
#include <QFileInfo>
#include <QDir>
#include <QInputDialog>
#include <QAbstractItemView>
#include <QDebug>
#include <QApplication>
// ======================
// 构造 / 析构
// ======================


MainWindow::MainWindow(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::MainWindow)
{
    m_ui->setupUi(this);
    m_ui->listWidget_show->setSelectionMode(QAbstractItemView::ExtendedSelection);
    m_ui->listWidget_hide->setSelectionMode(QAbstractItemView::ExtendedSelection);


    if (m_ui->comboBox_insert_ui->count() > 0) {
        m_uipath = m_ui->comboBox_insert_ui->currentText();
        m_jsonconfigwriter = new JsonConfigWriter(this, m_uipath);
    } else {
        m_jsonconfigwriter = nullptr;   // 先不创建
    }

   // ===== 用户相关初始化 =====
    m_userManager = new UserManager(
        m_ui->lineEdit_insert_user,
        m_ui->comboBox_insert_user,
        m_ui->button_add,
        m_ui->button_delete,
        m_ui->listWidget_hide,
        this
    );

    m_userConfigManager = new UserConfigManager(this);

    // ===== 信号槽连接 =====
    connect(m_ui->button_import_directory, SIGNAL(clicked()),
            this, SLOT(importDirectory()));
    connect(m_ui->button_hide, SIGNAL(clicked()), this, SLOT(moveToShow()));
    connect(m_ui->button_show, SIGNAL(clicked()), this, SLOT(moveToHide()));
    connect(m_ui->comboBox_insert_user, SIGNAL(currentIndexChanged(QString)),
            this, SLOT(onUserChanged(QString)));
    connect(m_ui->comboBox_insert_ui, SIGNAL(currentIndexChanged(QString)),
            this, SLOT(on_comboBox_insert_ui_currentIndexChanged(QString)));

    connect(m_userConfigManager, SIGNAL(userCopied(QString)),
            this, SLOT(onUserCopied(QString)));

    connect(m_userManager, SIGNAL(switchToUser(QString)),
            this, SLOT(onSwitchToUser(QString)));
}

MainWindow::~MainWindow()
{
    delete m_jsonconfigwriter;
    delete m_ui;
}

// ======================
// 槽实现
// ======================

// ======================
// 导入目录
// ======================
void MainWindow::importDirectory()
{
    QString dirPath = QFileDialog::getExistingDirectory(
        this,
        "Select the directory where the UI file is located"
    );
    if (dirPath.isEmpty())
        return;

    QStringList results;
    FileDialogHandler handler;
    handler.collectUiFiles(dirPath, results);

    foreach (QString f, results) {
        qDebug() << "Recursively find files:" << f;
        m_ui->comboBox_insert_ui->addItem(f);
    }
}

// ======================
// 从 show → hide
// ======================
void MainWindow::moveToShow()
{
    QList<QListWidgetItem*> selected = m_ui->listWidget_show->selectedItems();
    foreach (QListWidgetItem *item, selected) {
        QString text = item->text();
        m_ui->listWidget_hide->addItem(text);
        delete m_ui->listWidget_show->takeItem(m_ui->listWidget_show->row(item));
    }
}

// ======================
// 从 hide → show （保持原有顺序）
// ======================
void MainWindow::moveToHide()
{
    QList<QListWidgetItem*> selected = m_ui->listWidget_hide->selectedItems();
    foreach (QListWidgetItem *item, selected) {
        QString text = item->text();

        int originalIndex = m_objectOriginalIndex.value(text, m_ui->listWidget_show->count());
        int insertRow = m_ui->listWidget_show->count();
        for (int i = 0; i < m_ui->listWidget_show->count(); ++i) {
            QString existing = m_ui->listWidget_show->item(i)->text();
            if (m_objectOriginalIndex.value(existing) > originalIndex) {
                insertRow = i;
                break;
            }
        }

        m_ui->listWidget_show->insertItem(insertRow, text);
        delete m_ui->listWidget_hide->takeItem(m_ui->listWidget_hide->row(item));
    }
}

// ======================
// 保存配置到 JSON
// ======================
void MainWindow::on_button_save_clicked()
{
    QString user = m_ui->comboBox_insert_user->currentText();
    QString uiPath = m_ui->comboBox_insert_ui->currentText();
    if (uiPath.isEmpty()) {
        QMessageBox::warning(this, "Error", "Please select a UI file first!");
        return;
    }
    if (user.isEmpty()) {
        QMessageBox::warning(this, "Error", "Please select a user first!");
        return;
    }

    // 收集“已隐藏控件”
    QStringList hiddenCtrls;
    for (int i = 0; i < m_ui->listWidget_hide->count(); ++i) {
        hiddenCtrls << m_ui->listWidget_hide->item(i)->text();
    }

    if (m_jsonconfigwriter->Write_To_Ui_Json(user, hiddenCtrls)) {
        QMessageBox::information(this, "Success", "Configuration saved to:\n" + m_jsonconfigwriter->makeJsonPath());
    } else {
        QMessageBox::warning(this, "Failed", "Failed to save configuration!");
    }
}

// ======================
// 加载 UI + 恢复配置
// ======================
void MainWindow::loadUiForUser(const QString &uiPath, const QString &user)
{
    m_uipath = uiPath;
    m_ui->listWidget_show->clear();
    m_ui->listWidget_hide->clear();
    m_objectOriginalIndex.clear();

    UiObjectReader reader;
    QStringList objects = reader.readObjectNames(uiPath);
    for (int i = 0; i < objects.size(); ++i) {
        QString obj = objects.at(i);
        m_objectOriginalIndex[obj] = i;
        m_ui->listWidget_show->addItem(obj);
    }

    if (m_jsonconfigwriter && !user.isEmpty()) {

        QStringList hiddenCtrls;
        if (m_jsonconfigwriter->Read_Json_To_Ui(user, hiddenCtrls)) {
            for (int i = 0; i < hiddenCtrls.size(); ++i) {
                QString ctrl = hiddenCtrls.at(i);
                QList<QListWidgetItem*> found =
                    m_ui->listWidget_show->findItems(ctrl, Qt::MatchExactly);
                if (!found.isEmpty()) {
                    delete m_ui->listWidget_show->takeItem(
                               m_ui->listWidget_show->row(found.first()));
                    m_ui->listWidget_hide->addItem(ctrl);
                }
            }
        }
    }
}

// ======================
// 切换 UI 文件
// ======================
void MainWindow::on_comboBox_insert_ui_currentIndexChanged(const QString &uiPath)
{
    if (uiPath.isEmpty())
            return;
    m_uipath = uiPath;
    // 先更新 jsonconfigwriter（保证新的 uiPath 生效）
    if (m_jsonconfigwriter) {
        delete m_jsonconfigwriter;
        m_jsonconfigwriter = nullptr;
    }
    m_jsonconfigwriter = new JsonConfigWriter(this, uiPath);

    // ⭐ 更新到 UserManager 的 jsonconfigwriter
    m_userManager->updateUiPath(m_uipath);

    // 清空用户下拉框
    m_ui->comboBox_insert_user->clear();

    // 读取匹配的用户列表（交集）
    QStringList users = m_jsonconfigwriter->Match_Users_list();
    m_ui->comboBox_insert_user->addItems(users);
    // 优先恢复 last_user
     QString lastUser;
     if (m_jsonconfigwriter->readLastUser(lastUser)) {
         int idx = m_ui->comboBox_insert_user->findText(lastUser);
         if (idx >= 0) {
             m_ui->comboBox_insert_user->setCurrentIndex(idx);
             return; // 会自动触发 onUserChanged
         }
     }
     // 默认选第一个
         m_ui->comboBox_insert_user->setCurrentIndex(0);
         loadUiForUser(uiPath, m_ui->comboBox_insert_user->currentText());


    }

// ======================
// 切换用户
// ======================
void MainWindow::onUserChanged(const QString &user)
{
    if (!m_jsonconfigwriter) return;
       if (m_uipath.isEmpty())
           return;

    if (user.trimmed().isEmpty()) {
        loadUiForUser(m_uipath, QString());
        return;
    }

    loadUiForUser(m_uipath, user);
}

void MainWindow::onUserCopied(const QString &newUser)
{

    m_ui->comboBox_insert_user->clear();
    m_ui->comboBox_insert_user->addItems(m_jsonconfigwriter->Match_Users_list());

    int idx = m_ui->comboBox_insert_user->findText(newUser);
    m_ui->comboBox_insert_user->setCurrentIndex(idx >= 0 ? idx : -1);


    loadUiForUser(m_uipath, newUser);
}

void MainWindow::on_button_copy_clicked()
{
    QString srcUser = m_ui->comboBox_insert_user->currentText();

    if (m_uipath.isEmpty() || srcUser.isEmpty()) {
        QMessageBox::warning(this, tr("Attention"), tr("Please select a user before copying."));
        return;
    }

    bool ok;
    QString newUser = QInputDialog::getText(this, tr("Copy user configuration"),
                                            tr("Please enter the new user:"),
                                            QLineEdit::Normal, QString(), &ok);
    if (!ok || newUser.isEmpty())
        return;

    QString errorMsg;
    if (!m_userConfigManager->copyUser( srcUser, newUser, errorMsg)) {
        QMessageBox::warning(this, tr("Failed"), errorMsg);
    }
}

void MainWindow::onSwitchToUser(const QString &user)
{
    QString uiPath = m_ui->comboBox_insert_ui->currentText();

    int idx = m_ui->comboBox_insert_user->findText(user);
    if (idx >= 0) {
        m_ui->comboBox_insert_user->setCurrentIndex(idx);
    }

    loadUiForUser(uiPath, user);
}

